<template>
  <el-container class="layout-container">
    <el-aside :width="isCollapse ? '64px' : '200px'">
      <div class="logo-container">
        <el-icon :size="24" class="logo-icon">
          <Monitor />
        </el-icon>
        <h1 class="logo-title" :class="{ 'collapsed': isCollapse }">后台管理系统</h1>
      </div>
      <el-menu :default-active="activeMenu" class="el-menu-vertical" :collapse="isCollapse" background-color="#304156"
        text-color="#fff" active-text-color="#409EFF" router>
        
        <!-- 动态菜单 -->
        <template v-for="menu in menus" :key="menu.id">
          <!-- 有子菜单的情况 -->
          <el-sub-menu v-if="menu.children && menu.children.length > 0" :index="menu.path">
            <template #title>
              <el-icon>
                <component :is="getMenuIcon(menu.path)" />
              </el-icon>
              <span>{{ menu.title }}</span>
            </template>
            <el-menu-item v-for="child in menu.children" :key="child.id" :index="child.path">
              <el-icon>
                <component :is="getMenuIcon(child.path)" />
              </el-icon>
              <span>{{ child.title }}</span>
            </el-menu-item>
          </el-sub-menu>
          
          <!-- 没有子菜单的情况 -->
          <el-menu-item v-else :index="menu.path">
            <el-icon>
              <component :is="getMenuIcon(menu.path)" />
            </el-icon>
            <template #title>{{ menu.title }}</template>
          </el-menu-item>
        </template>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header>
        <div class="header-left">
          <el-button type="text" @click="toggleCollapse" class="collapse-btn">
            <el-icon :size="20">
              <Fold v-if="!isCollapse" />
              <Expand v-else />
            </el-icon>
          </el-button>
          <el-breadcrumb separator="/" v-if="route.path !== '/home'" class="breadcrumb">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="index" :to="item.path">
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
          <span v-else class="breadcrumb">首页</span>
        </div>
        <div class="header-right">
          <el-dropdown>
            <span class="user-info">
              {{ user.nickName == null ? user.username : user.nickName }} <el-icon>
                <ArrowDown />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="$router.push('/profile')">个人信息</el-dropdown-item>
                <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-main>
        <router-view v-slot="{ Component }">
          <transition name="fade-transform" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  HomeFilled,
  Setting,
  Fold,
  Expand,
  ArrowDown,
  Monitor,
  Document,
  User,
  Bell,
  UserFilled
} from '@element-plus/icons-vue'
import { getUserMenu } from '@/api/permission'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const isCollapse = ref(false)
const user = ref(JSON.parse(localStorage.getItem("user")))
const menus = ref([])

// 获取用户菜单
const fetchUserMenu = async (retryCount = 0) => {
  // 确保有token才请求菜单
  const token = localStorage.getItem('token')
  if (!token) {
    console.error('获取菜单失败: 没有token')
    ElMessage.error('未登录或登录状态失效，请重新登录')
    router.push('/login')
    return
  }

  try {
    console.log('开始获取菜单数据，使用token:', token)
    const res = await getUserMenu()
    if (res && res.data) {
      menus.value = res.data
      console.log('加载菜单成功:', menus.value)
    } else {
      console.error('菜单数据格式错误:', res)
      // 如果数据为空且重试次数小于3，则重试
      if (retryCount < 3) {
        console.log(`尝试重新获取菜单 (${retryCount + 1}/3)...`)
        setTimeout(() => fetchUserMenu(retryCount + 1), 1000)
      } else {
        ElMessage.error('菜单数据格式错误')
      }
    }
  } catch (error) {
    console.error('获取菜单失败:', error)
    // 如果失败且重试次数小于3，则重试
    if (retryCount < 3) {
      console.log(`尝试重新获取菜单 (${retryCount + 1}/3)...`)
      setTimeout(() => fetchUserMenu(retryCount + 1), 1000)
    } else {
      ElMessage.error('获取菜单失败')
    }
  }
}

// 根据路径获取图标
const getMenuIcon = (path) => {
  // 精确路径匹配
  const iconMap = {
    '/home': HomeFilled,
    '/system/user': User,
    '/system/role': UserFilled,
    '/system/permission': Setting,
    '/system/log': Document,
    '/system/notice': Bell,
    '/profile': User
  }
  
  // 先尝试精确匹配
  if (iconMap[path]) {
    return iconMap[path]
  }
  
  // 如果没有精确匹配，尝试部分路径匹配
  for (const key in iconMap) {
    if (path.includes(key) || key.includes(path)) {
      return iconMap[key]
    }
  }
  
  // 默认返回文档图标
  return Document
}

// 当前激活的菜单
const activeMenu = computed(() => route.path)

// 面包屑导航数据
const breadcrumbList = computed(() => {
  const matched = route.matched.slice(1)
  return matched.map(item => ({
    title: item.meta.title,
    path: item.path.startsWith('/') ? item.path : `/${item.path}`
  }))
})

const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

const handleLogout = () => {
  localStorage.removeItem("user")
  localStorage.removeItem("token")
  router.push('/login')
}

// 组件挂载时获取菜单
onMounted(() => {
  console.log('Layout组件挂载，准备获取菜单数据')
  // 延迟一点获取菜单，确保token已被正确加载
  setTimeout(() => {
    fetchUserMenu()
  }, 100)
})
</script>

<style scoped>
.layout-container {
  height: 100vh;
}

.el-aside {
  background-color: #304156;
  transition: width 0.3s;
  overflow: hidden;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2b3a4a;
  overflow: hidden;
  padding: 0 10px;
  gap: 10px;
}

.logo-icon {
  color: #409EFF;
  flex-shrink: 0;
}

.logo-title {
  color: #fff;
  font-size: 18px;
  margin: 0;
  white-space: nowrap;
  transition: all 0.3s;
}

.logo-title.collapsed {
  width: 0;
  font-size: 0;
}

.el-menu-vertical {
  height: calc(100% - 60px);
  border-right: none;
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: 200px;
}

.el-header {
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.el-main {
  background-color: #f0f2f5;
  padding: 20px;
}

/* 路由切换动画 */
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(-30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

.collapse-btn {
  padding: 0;
  margin-right: 8px;
}

.collapse-btn :deep(.el-icon) {
  font-size: 20px;
  color: #303133;
}

.breadcrumb {
  font-size: 14px;
  color: #303133;
}

.breadcrumb :deep(.el-breadcrumb__item) {
  font-size: 14px !important;
}
</style>